export default {
  namespaced: true,
  state: {
    city: '定位中...'
  },
  mutations: {
    SET_CITY(state, city) {
      state.city = city
    }
  },
  actions: {
    async getLocation({ commit }) {
      try {
        const position = await new Promise((resolve, reject) => {
          if (!navigator.geolocation) {
            reject(new Error('不支持地理位置'))
            return
          }
          navigator.geolocation.getCurrentPosition(resolve, reject)
        })
        
        // 这里使用百度地图 API 进行经纬度转换为城市名
        const { latitude, longitude } = position.coords
        const url = `https://api.map.baidu.com/reverse_geocoding/v3/?ak=YOUR_BAIDU_MAP_AK&output=json&coordtype=wgs84ll&location=${latitude},${longitude}`
        
        const response = await fetch(url)
        const data = await response.json()
        
        if (data.status === 0) {
          commit('SET_CITY', data.result.addressComponent.city)
        } else {
          commit('SET_CITY', '定位失败')
        }
      } catch (error) {
        commit('SET_CITY', '定位失败')
        console.error('获取位置失败:', error)
      }
    }
  }
}